package com.ayf.payment.game.api.controller.platform;

import com.ayf.payment.game.api.utils.FtpUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Description:
 * @Author: zh-liang
 * @Date: 2022-03-17 14:58
 */
@RestController
@RequestMapping("/t1/file")
public class File1Controller {

    /**
     * 文件下载
     *
     * @param fileName
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/downloadImg")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        String traceId = SnowFlakeUtils.getUniqueId();
        ServletOutputStream outputStream = null;
        try {
            byte[] bytes = FtpUtil.downloadXYFile("", fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Cache-Control", "No-cache");
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (Exception e) {
            LogPortal.error("[{}]文件下载发生[{}]异常,异常信息为[{}]", e, traceId, e.getClass().getSimpleName(), e.getMessage());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                LogPortal.error("文件上传关闭流时发生IOException，异常信息为: {}", e, e.getMessage());
            }
        }
    }
}
